package service

import (
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"onvif_server/internal/library/setting"
	"onvif_server/internal/model"
	"onvif_server/internal/repository"
	"onvif_server/pkg/jwt"
	"onvif_server/pkg/network"
	"onvif_server/pkg/storage"
	"onvif_server/pkg/subscribe"
	"time"
)

type Config struct {
	CameraRootPath string `help:"默认摄像头文件写入目录" default:"/data_dir/video/live"`
	UploadMaxSize  int64  `help:"最大上传大小，默认100M" default:"104857600"`
	Endpoint       string `internal:"true"`
	Addr           string `internal:"true"`
	Port           uint   `internal:"true"`
	StorageRoot    string `internal:"true"`
	StorageUrl     string `internal:"true"`
}

type Service struct {
	config   *Config
	deviceId string
	log      *zap.Logger
	jwt      *jwt.JWT
	loc      *time.Location
	tm       repository.Transaction

	settingLib *setting.Setting
}

func NewService(deviceId string, conf *Config, tm repository.Transaction, log *zap.Logger, jwt *jwt.JWT, loc *time.Location, settingLib *setting.Setting) *Service {
	return &Service{
		config:   conf,
		deviceId: deviceId,
		log:      log.Named("service"),
		jwt:      jwt,
		tm:       tm,
		loc:      loc,

		settingLib: settingLib,
	}
}

func WithTopicToSubscribers(list []*model.Subscription, topic string) []subscribe.Subscriber {
	res := make([]subscribe.Subscriber, 0)
	for i := range list {
		if list[i].TopicIndex(topic) {
			res = append(res, subscribe.Subscriber{
				Url: list[i].ApiUrl,
				Key: list[i].AppKey,
			})
		}
	}
	return res
}

type netInterfaces struct {
	Default    string
	Interfaces map[string]*network.NetInterface
}

// getNetInterfaces 获取网卡信息，目前都只是支持ipv4
func (s *Service) getNetInterfaces() *netInterfaces {
	ifcs := network.GetNetInterfaces()
	res := &netInterfaces{
		Interfaces: make(map[string]*network.NetInterface),
	}
	def := s.settingLib.GetWithDefault(setting.NetworkDefault, "").(string)
	exists := false
	for i := range ifcs {
		res.Interfaces[ifcs[i].Name] = &ifcs[i]
		if ifcs[i].Name == def {
			exists = true
		}
	}
	//设置的网卡不存在了，更新成默认第一个
	if !exists && len(ifcs) > 0 {
		def = ifcs[0].Name
		_err := s.settingLib.Store(setting.NetworkDefault, def)
		if _err != nil {
			s.log.Error("更新默认网卡失败", zap.String("name", def), zap.Error(_err))
		}
	}
	res.Default = def
	return res
}

// getStorage 获取存储实例
func (s *Service) getStorage() (_ storage.Storage, err error) {
	driver := s.settingLib.GetWithDefault(setting.StorageDriver, "").(string)
	switch driver {
	case storage.DriverOss:
		conf := storage.OssConfig{}
		err = json.Unmarshal([]byte(s.settingLib.GetWithDefault(setting.StorageOss, "").(string)), &conf)
		if err != nil {
			return
		}
		return storage.NewOss(&conf, s.loc)
	case storage.DriverCos:
		conf := storage.CosConfig{}
		err = json.Unmarshal([]byte(s.settingLib.GetWithDefault(setting.StorageCos, "").(string)), &conf)
		if err != nil {
			return
		}
		return storage.NewCos(&conf, s.loc)
	default:
		return storage.NewLocal(&storage.LocalConfig{Root: s.config.StorageRoot, Url: s.config.StorageUrl})
	}
}

func (s *Service) getEndpoint(ip string) string {
	if s.config.Endpoint != "" {
		return s.config.Endpoint
	}
	if ip == "" {
		ip = "127.0.0.1"
		if s.config.Addr != "" && s.config.Addr != "0.0.0.0" {
			ip = s.config.Addr
		}
	}
	return fmt.Sprintf("http://%s:%d", ip, s.config.Port)
}
